<template>
  <div class="aurora-container">
    <div class="aurora-background">
      <div class="aurora-dot"></div>
      <div class="aurora-dot"></div>
      <div class="aurora-dot"></div>
    </div>

    <div class="glass-panel">
      <div class="assistant-header">
        <div class="final-nono" :class="{ thinking: isLoading }">
          <div class="nono-wing left"></div>
          <div class="nono-wing right"></div>
          <div class="nono-body">
              <div class="nono-ear left"></div>
              <div class="nono-ear right"></div>
              <div class="nono-panel-line-v"></div>
              <div class="nono-panel-line-h"></div>
              <div class="nono-visor">
                  <div class="nono-visor-glare"></div>
                  <div class="nono-eye left"></div>
                  <div class="nono-eye right"></div>
              </div>
          </div>
        </div>
        <div class="header-text">
          <h1>智能AI助手</h1>
          <p>在线解答，提供支持</p>
        </div>
      </div>

      <div class="chat-container" ref="chatContainerRef">
        <div v-for="(msg, index) in messages" :key="index" class="message-row" :class="[msg.from === 'user' ? 'user-message' : 'ai-message']">
          <div class="message-bubble">
            <div v-if="msg.isLoading" class="typing-indicator"></div>
            <div v-else class="message-content" v-html="formatMessage(msg.content)"></div>
            
            <el-button 
              v-if="msg.from === 'ai' && !msg.isLoading && msg.content"
              class="speech-button"
              :icon="speechService.isSpeaking.value ? Mute : Reading" 
              @click="handleBubbleSpeech(msg.content)"
              circle
            />
          </div>
        </div>
      </div>

      <div class="input-area-wrapper">
        <div class="quick-prompts">
          <el-button @click="useQuickPrompt('给我一些教学灵感')" round><el-icon><Opportunity /></el-icon>教学灵感</el-button>
          <el-button @click="useQuickPrompt('我们来角色扮演，你是一个学生')" round><el-icon><User /></el-icon>角色扮演</el-button>
          <el-button @click="useQuickPrompt('放松一下，讲个笑话吧')" round><el-icon><IceTea /></el-icon>放松一下</el-button>
        </div>
        <div class="chat-input-area">
          <el-input
            v-model="userInput"
            placeholder="向AI助手提问..."
            type="textarea"
            :autosize="{ minRows: 1, maxRows: 4 }"
            @keyup.enter.exact.prevent="sendMessage"
            resize="none"
            class="aurora-input"
          />
          <el-button class="send-button" @click="sendMessage" :disabled="isLoading || !userInput.trim()" circle>
            <el-icon><Promotion /></el-icon>
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted, onBeforeUnmount } from 'vue';
import aiAssistantService from '../../services/aiAssistantService.js';
import speechService from '../../services/speechService.js'; // 导入语音服务
import MarkdownIt from 'markdown-it';
import { Promotion, Opportunity, User, IceTea, Reading, Mute } from '@element-plus/icons-vue';

const userInput = ref('');
const messages = ref([]);
const isLoading = ref(false);
const chatContainerRef = ref(null);
const md = new MarkdownIt();

const useQuickPrompt = (prompt) => {
  userInput.value = prompt;
  sendMessage();
};

const scrollToBottom = () => {
  nextTick(() => {
    if (chatContainerRef.value) {
      chatContainerRef.value.scrollTop = chatContainerRef.value.scrollHeight;
    }
  });
};

const formatMessage = (content) => md.render(String(content || ''));

const sendMessage = async () => {
  if (!userInput.value.trim() || isLoading.value) return;

  const userQuestion = userInput.value;
  messages.value.push({ from: 'user', content: userQuestion });
  userInput.value = '';
  scrollToBottom();

  isLoading.value = true;
  messages.value.push({ from: 'ai', content: '', isLoading: true });
  scrollToBottom();

  try {
    const reply = await aiAssistantService.ask(messages.value.slice(0, -1)); // 发送不包含加载占位符的历史记录
    messages.value[messages.value.length - 1] = { from: 'ai', content: reply, isLoading: false };
  } catch (error) {
    messages.value[messages.value.length - 1] = { from: 'ai', content: '出现错误，请稍后再试。', isLoading: false };
  } finally {
    isLoading.value = false;
    scrollToBottom();
  }
};

// 为单条消息添加朗读功能
const handleBubbleSpeech = (content) => {
  // 从HTML中提取纯文本进行朗读
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = formatMessage(content);
  speechService.toggleSpeech(tempDiv.textContent || tempDiv.innerText || '');
};

onMounted(() => {
  messages.value.push({from: 'ai', content: '您好，AI助手已准备就绪，随时为您服务。'})
});

// 组件卸载时停止朗读
onBeforeUnmount(() => {
  speechService.stop();
});
</script>

<style scoped>
/* ======================== */
/* 主题：星尘 · NoNo最终修复版 */
/* ======================== */
.aurora-container {
  height: calc(100vh - 100px); position: relative;
  background-color: #0c0a1d; overflow: hidden; border-radius: 16px;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', sans-serif;
  --theme-color: #00D1FF; /* NoNo's Cyan */
  --user-bg: rgba(0, 209, 255, 0.15);
  --user-text: #E0F8FF;
  --user-border: var(--theme-color);
  --text-primary: #FFFFFF;
  --text-secondary: #CACED4;
  --el-color-primary: var(--theme-color);
}
.aurora-background { position: absolute; width: 100%; height: 100%; pointer-events: none; }
.aurora-dot { position: absolute; border-radius: 50%; filter: blur(80px); animation: aurora-flow 25s infinite linear; }
.aurora-dot:nth-child(1) { top: -20%; left: -20%; width: 400px; height: 400px; background: rgba(0, 209, 255, 0.3); }
.aurora-dot:nth-child(2) { top: 40%; right: -30%; width: 500px; height: 500px; background: rgba(139, 92, 246, 0.2); animation-delay: -8s; }
.aurora-dot:nth-child(3) { bottom: -20%; left: 30%; width: 300px; height: 300px; background: rgba(16, 185, 129, 0.2); animation-delay: -16s; }
@keyframes aurora-flow { 0% { transform: translate(0, 0) rotate(0deg); } 50% { transform: translate(100%, 80%) rotate(180deg); } 100% { transform: translate(0, 0) rotate(360deg); } }
.glass-panel { height: 100%; width: 100%; position: relative; z-index: 1; display: flex; flex-direction: column; background: rgba(17, 24, 39, 0.6); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); border: 1px solid rgba(255, 255, 255, 0.1); }
.assistant-header { display: flex; align-items: center; padding: 20px; flex-shrink: 0; }
.header-text h1 { font-size: 1.5rem; font-weight: 600; color: var(--text-primary); margin: 0; }
.header-text p { margin: 4px 0 0 0; color: var(--text-secondary); font-size: 0.8rem; }
.chat-container { flex-grow: 1; overflow-y: auto; padding: 0 24px; }
.message-row { display: flex; margin-bottom: 20px; animation: slide-up 0.5s ease-out; align-items: flex-start; gap: 10px;}
@keyframes slide-up { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
.message-bubble { position: relative; padding: 14px 20px; border-radius: 12px; max-width: 80%; line-height: 1.7; background: rgba(255,255,255,0.08); }
.message-content :deep(p) { margin-top: 0; margin-bottom: 1em; }
.message-content :deep(p:last-child) { margin-bottom: 0; }
.message-content :deep(ul), .message-content :deep(ol) { padding-left: 20px; }
.ai-message { color: var(--text-primary); }
.user-message { justify-content: flex-end; }
.user-message .message-bubble { background: var(--user-bg); color: var(--user-text); border: 1px solid var(--user-border); }
.typing-indicator { width: 40px; height: 20px; position: relative; animation: typing-container-fade 0.5s; }
@keyframes typing-container-fade { from { opacity: 0; } to { opacity: 1; } }
.typing-indicator::after { content: ''; width: 6px; height: 6px; position: absolute; border-radius: 50%; background: var(--theme-color); box-shadow: 0 0 8px var(--theme-color); animation: typing-dot-bounce 1.5s ease-in-out infinite; }
@keyframes typing-dot-bounce { 0%, 100% { transform: translateY(10px); } 50% { transform: translateY(-10px); } }
.input-area-wrapper { flex-shrink: 0; padding: 20px; background: rgba(17, 24, 39, 0.5); border-top: 1px solid rgba(255, 255, 255, 0.1); position: relative; z-index: 10; }
.quick-prompts { display: flex; gap: 12px; margin-bottom: 16px; flex-wrap: wrap; }
.quick-prompts .el-button { background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.2); color: var(--text-secondary); }
.quick-prompts .el-button:hover { background: rgba(255,255,255,0.2); color: var(--text-primary); border-color: rgba(255,255,255,0.3); }
.quick-prompts .el-icon { margin-right: 6px; }
.chat-input-area { display: flex; align-items: flex-end; gap: 12px; }
.aurora-input { flex: 1; }
.aurora-input :deep(.el-textarea__inner) { background: rgba(0,0,0,0.2); border-radius: 12px; box-shadow: none; border: 1px solid rgba(255,255,255,0.2); font-size: 1rem; color: var(--text-primary); padding: 12px 16px; }
.aurora-input :deep(.el-textarea__inner):focus { border-color: var(--theme-color); }
.aurora-input :deep(.el-textarea__inner)::placeholder { color: var(--text-secondary); }
.send-button { flex-shrink: 0; width: 48px; height: 48px; background-color: var(--theme-color); color: #fff; transition: all 0.3s ease; border: none; box-shadow: 0 4px 20px rgba(0, 209, 255, 0.3); }
.send-button:hover { transform: scale(1.1); box-shadow: 0 6px 25px rgba(0, 209, 255, 0.4); }
.send-button .el-icon { font-size: 20px; transition: transform 0.3s ease; }
.send-button:hover .el-icon { transform: rotate(-30deg); }

/* ================== */
/* CSS NoNo 机器人    */
/* ================== */
.final-nono {
  width: 54px; height: 54px; position: relative;
  margin-right: 16px; animation: nono-float 3s ease-in-out infinite;
}
@keyframes nono-float { 50% { transform: translateY(-4px); } }
.final-nono.thinking { animation: nono-float 1s ease-in-out infinite; }

.nono-body {
  width: 100%; height: 100%;
  background: radial-gradient(circle at 50% 40%, #FFFFFF, #DDE2E8);
  border-radius: 50%; border: 1px solid #B0B9C8;
  box-shadow: 0 4px 8px rgba(0,0,0,0.2);
  position: relative; overflow: visible;
}
.nono-panel-line-v, .nono-panel-line-h {
  position: absolute; background: #C8D0DC; z-index: 1;
}
.nono-panel-line-v { width: 1px; height: 100%; top: 0; left: 50%; transform: translateX(-50%);}
.nono-panel-line-h { height: 1px; width: 100%; left: 0; top: 50%; transform: translateY(-50%);}

.nono-ear {
  width: 14px; height: 18px;
  background-color: #FFFFFF;
  border: 1px solid #B0B9C8;
  position: absolute; top: -6px; z-index: 0;
  clip-path: polygon(50% 0%, 100% 100%, 0% 100%);
}
.nono-ear::after {
  content: ''; position: absolute;
  width: 100%; height: 100%; top: 0; left: 0;
  background: radial-gradient(circle at 50% 100%, var(--theme-color), transparent 70%);
  opacity: 0.5;
}
.nono-ear.left { left: 8px; transform: rotate(-15deg); }
.nono-ear.right { right: 8px; transform: rotate(15deg); }
.final-nono.thinking .nono-ear.left { animation: nono-ear-twitch-left 0.5s ease-in-out infinite alternate; }
.final-nono.thinking .nono-ear.right { animation: nono-ear-twitch-right 0.5s ease-in-out infinite alternate; }
@keyframes nono-ear-twitch-left { to { transform: rotate(-20deg) translateY(-2px); } }
@keyframes nono-ear-twitch-right { to { transform: rotate(20deg) translateY(-2px); } }


.nono-wing {
  width: 18px; height: 18px;
  background-color: var(--theme-color);
  position: absolute; top: 50%;
  transform: translateY(-50%);
  filter: blur(5px);
  box-shadow: 0 0 12px var(--theme-color), 0 0 18px var(--theme-color);
  clip-path: polygon(0% 50%, 100% 0%, 100% 100%);
  animation: nono-wing-flap 3s ease-in-out infinite;
}
@keyframes nono-wing-flap { 50% { transform: translateY(-50%) scale(1.1); opacity: 0.8; } }
.nono-wing.left { left: -10px; }
.nono-wing.right { right: -10px; transform: translateY(-50%) scaleX(-1); animation-name: nono-wing-flap-right; }
@keyframes nono-wing-flap-right { 50% { transform: translateY(-50%) scaleX(-1) scale(1.1); opacity: 0.8; } }


.nono-visor {
  width: 75%; height: 75%; background: #222;
  border-radius: 50%; position: absolute; z-index: 2;
  top: 12.5%; left: 12.5%;
  display: flex; justify-content: center; align-items: center;
  gap: 8px;
}
.nono-visor-glare {
  width: 50%; height: 25%; background: rgba(255,255,255,0.1);
  border-radius: 50%; position: absolute; top: 15%; left: 15%;
  transform: rotate(-30deg);
}
.nono-eye {
  width: 6px; height: 16px; background: var(--theme-color);
  border-radius: 3px; box-shadow: 0 0 8px var(--theme-color);
  transition: all 0.2s ease;
}
.final-nono.thinking .nono-eye {
  background: #FFFFFF;
  box-shadow: 0 0 12px #FFFFFF;
  animation: nono-eye-blink 1s infinite;
}
@keyframes nono-eye-blink { 50% { transform: scaleY(0.1); } }


/* Speech Button Styles */
.ai-message .message-bubble:hover .speech-button {
  opacity: 1;
}

.speech-button {
  position: absolute;
  top: 8px;
  right: 8px;
  opacity: 0;
  transition: opacity 0.3s ease-in-out;
  background-color: rgba(255, 255, 255, 0.1) !important;
  border: none !important;
  color: #fff !important;
  font-size: 16px;
  width: 32px;
  height: 32px;
}

.speech-button:hover {
  background-color: rgba(255, 255, 255, 0.2) !important;
}
</style>